package com.mdd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mdd.common.BaseContext;
import com.mdd.common.CustomException;
import com.mdd.dto.OrderDto;
import com.mdd.mapper.OrderMapper;
import com.mdd.pojo.*;
import com.mdd.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;

    /**
     *账单提交
     * @param orders
     */
    @Override
    @Transactional
    public void submit(Orders orders) {
        //获取当前登录用户的Id
        Long userId = BaseContext.getCurrentId();
        //获取当前用户的购物车信息
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(queryWrapper);
        if (shoppingCarts==null||shoppingCarts.size()==0) throw new CustomException("购物车为空");

        //设置账单的userId
        orders.setUserId(userId);
        //设置账单的创建和结账时间
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());

        //查询用户信息
        User user = userService.getById(userId);
        //设置账单的用户名
        orders.setUserName(user.getName());
        //账单的手机号
        orders.setPhone(user.getPhone());

        //查询地址信息
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        if (addressBook==null) throw new CustomException("请设置您的地址信息");
        //设置账单的地址信息
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());

        //设置账单的状态

        orders.setStatus(4);
        //设置订单号
        long id = IdWorker.getId();
        orders.setNumber(String.valueOf(id));
        orders.setId(id);

        //设置账单的实收金额和订单明细集合
        Collection<OrderDetail> orderDetails = new ArrayList<>();
        //应对多线程高并发，保证线程安全
        AtomicInteger amount = new AtomicInteger(0);
        for (ShoppingCart shoppingCart : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(id);
            orderDetail.setNumber(shoppingCart.getNumber());
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor());
            orderDetail.setDishId(shoppingCart.getDishId());
            orderDetail.setSetmealId(shoppingCart.getSetmealId());
            orderDetail.setName(shoppingCart.getName());
            orderDetail.setImage(shoppingCart.getImage());
            orderDetail.setAmount(shoppingCart.getAmount());
            amount.addAndGet(shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber())).intValue());
            orderDetails.add(orderDetail);
        }
        orders.setAmount(new BigDecimal(amount.intValue()));

        //向订单表插入这个订单信息
        super.save(orders);
        //向账单明细表里批量添加账单明细
        orderDetailService.saveBatch(orderDetails);

        //删除购物车数据
        shoppingCartService.remove(queryWrapper);
    }

    /**
     * 根据条件展示账单
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public Page<OrderDto> showUserOrder(int page, int pageSize,Long currentId, Long number, String beginTime,String endTime)     {
        //获取当前用户所有的订单的基本信息
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(currentId!=null,Orders::getUserId,currentId)
                .orderByDesc(Orders::getOrderTime)
                .eq(number!=null,Orders::getNumber,number)
                .between(beginTime!=null&&endTime!=null,Orders::getOrderTime,beginTime,endTime);
        super.page(ordersPage,queryWrapper);

        //将分页基本信息拷贝被orderDtoPage
        Page<OrderDto> orderDtoPage = new Page<>();
        BeanUtils.copyProperties(ordersPage,orderDtoPage,"records");

        //获取当前页的数据
        List<Orders> records = ordersPage.getRecords();
        List<OrderDto> orderDtos = new ArrayList<>();
        orderDtoPage.setRecords(orderDtos);
        for (Orders record : records) {
            OrderDto orderDto = new OrderDto();
            BeanUtils.copyProperties(record,orderDto,"orderDetails");
            //获取当前订单Id
            Long id = record.getId();
            //获取当前账单的明细
            LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(OrderDetail::getOrderId,id);
            List<OrderDetail> details = orderDetailService.list(wrapper);
            //将账单明细封装给orderDto
            orderDto.setOrderDetails(details);

            //设置orderDto的UserName
            orderDto.setUserName(record.getConsignee());

            orderDtos.add(orderDto);
        }
        return orderDtoPage;
    }

}
